//
// Created by leisurexi on 11/22/20.
// file_client.c
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <lib/packet.h>

#define BUF_SIZE 1024

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char *argv[]) {
    int sock, recv_cnt, recv_len ;
    struct packet read_buf, write_buf;
    struct sockaddr_in server_addr;

    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1)
        error_handling("socket() error");

    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);
    server_addr.sin_port = htons(atoi(argv[2]));

    if (connect(sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
        error_handling("connect() error");
    else
        puts("Connected......");

    fputs("Input file full path: ", stdout);
    fgets(write_buf.data, sizeof(write_buf.data), stdin);
    write_buf.len = strlen(write_buf.data);

    write(sock, &write_buf, sizeof(write_buf));

    // 1: Read the data length.
    read(sock, &read_buf, 4);

    // 2: Read: data while recv_len more than date length.
    while (recv_len < read_buf.len) {
        recv_cnt = read(sock, read_buf.data, read_buf.len);
        recv_len += recv_cnt;
    }

    // 3: Write data to file.
    FILE *fp = fopen("/tmp/test.txt", "w");
    fputs(read_buf.data, fp);

    close(sock);
    return 0;
}
